package com.ktjiaoyu.crm.realm;

import com.ktjiaoyu.crm.pojo.Role;
import com.ktjiaoyu.crm.pojo.User;
import com.ktjiaoyu.crm.service.RightService;
import com.ktjiaoyu.crm.service.RoleService;
import com.ktjiaoyu.crm.service.UserService;
import com.ktjiaoyu.crm.util.RedisTemplateUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.Set;

/**
 * @ClassName : MyShiroRealm
 * @Description :
 * @Author : Lzz
 * @Date: 2023/11/27 10:39:23
 */
public class MyShiroRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;


    @Resource
    private RoleService roleService;

    @Resource
    private RightService rightService;

    @Resource
    private RedisTemplateUtil redisTemplateUtil;

    //Redis中缓存数据的key前缀
    private String SHIRO_LOGIN_COUNT = "shiro_login_count:"; //登录次数计数
    private String SHIRO_IS_LOCK = "shirl_is_lock:";         //锁定用户登录


    /**
     * 认证
     * @param token the authentication token containing the user's principal and credentials.
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        //每次访问，登录次数+1
        redisTemplateUtil.incr(SHIRO_LOGIN_COUNT+usernamePasswordToken.getUsername(),1);
        //计数大于 5 时，设置用户被锁定一小时，清空登录计数
        if(Integer.parseInt(redisTemplateUtil.get(SHIRO_LOGIN_COUNT+usernamePasswordToken.getUsername()).toString())>5){
            redisTemplateUtil.set(SHIRO_IS_LOCK+usernamePasswordToken.getUsername(),"LOCK");
            //锁定用户一小时，设置Redis过期时间，单位S
            redisTemplateUtil.expire(SHIRO_IS_LOCK+usernamePasswordToken.getUsername(),3600);
            //清空登录计数
            redisTemplateUtil.del(SHIRO_LOGIN_COUNT+usernamePasswordToken.getUsername());
        }
        //判断用户是否锁定
        if("LOCK".equals(redisTemplateUtil.get(SHIRO_IS_LOCK+usernamePasswordToken.getUsername()))) throw new DisabledAccountException();
        //从token中获取用户名
        String username = usernamePasswordToken.getUsername();
        //调用数据库查询方法根据用户名查询用户信息
        User user = userService.findUserByUsrName(username);
        if(user == null) throw new UnknownAccountException();   //账号错误
        if(user.getUsrFlag()==null || user.getUsrFlag().intValue()==0) throw new LockedAccountException();  //账号是否锁定

        return new SimpleAuthenticationInfo(user,user.getUsrPassword(), ByteSource.Util.bytes("czkt"),getName());
    }

    /**
     * 授权
     * @param principals the primary identifying principals of the AuthorizationInfo that should be retrieved.
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取主体身份
        User user = (User) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //动态授权：从数据库中获取当前主体用户所拥有的权限
        //info.addRole(user.getRoleName());
        Role role = roleService.findRoleByUserId(user.getUsrId());
        info.addRole(role.getRoleName());
        //根据角色ID查询该用户所拥有的权限列表
        Set<String> rights = rightService.findRightsByRoleId(user.getUsrRoleId());
        info.addStringPermissions(rights);
        return info;
    }

    /**
     * 清空当前认证用户权限缓存
     */
    public void clearMyCachedAuthorizationInfo() {
        clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }

    /**
     * 清空所有用户权限缓存
     */
    public void clearAllCachedAuthorizationInfo() {
        if (this.isAuthorizationCachingEnabled()) { // 权限缓存是否可用
            Cache<Object, AuthorizationInfo> cache = null;
            CacheManager cacheManager = this.getCacheManager();
            if (cacheManager != null) {
                String cacheName = this.getAuthorizationCacheName(); // 获得权限缓存名称
                cache = cacheManager.getCache(cacheName); // 获得权限缓存
            }
            if (cache != null) {
                cache.clear(); // 清空
            }
        }
    }


}
